<template>
  <div class="bg-[#ececec] h-screen overflow-auto">
    <router-view v-slot="{ Component }">
      <keep-alive :include="['Question']">
        <component :is="Component" />
      </keep-alive>
    </router-view>

    <!-- 全局语音通话弹窗 -->
    <VoiceCallDialog
      v-model:visible="showIncomingCall"
      :call-data="incomingCallData"
      :base-url="incomingCallBaseUrl"
    />

    <!-- 全局聊天面板 -->
    <el-dialog
      v-model="showGlobalChat"
      :title="globalChatTitle"
      width="520px"
      :close-on-click-modal="false"
      destroy-on-close
      class="global-chat-dialog"
      @close="handleChatClose"
    >
      <div class="chat-container">
        <div class="chat-main">
          <!-- 消息列表 -->
          <div ref="messageListRef" class="message-list">
            <div
              v-for="message in globalChatMessages"
              :key="message.id"
              class="message-item"
              :class="{ 'self': message.isSelf }"
            >
              <div class="message-content">
                <div class="message-header">
                  <span class="sender-name">{{ message.senderName }}</span>
                  <span class="message-time">{{ formatMessageTime(message.timestamp) }}</span>
                </div>
                <!-- 文本消息 -->
                <div v-if="message.msgType === 0" class="message-text">
                  {{ message.content }}
                </div>
                <!-- 图片消息 -->
                <div v-else-if="message.msgType === 1" class="message-media">
                  <el-image
                    :src="message.content"
                    :preview-src-list="[message.content]"
                    fit="cover"
                    class="message-image"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon><Picture /></el-icon>
                        <span>加载失败</span>
                      </div>
                    </template>
                  </el-image>
                </div>
                <!-- 音视频消息 -->
                <div v-else-if="message.msgType === 2" class="message-media">
                  <video
                    v-if="isVideoFile(message.content)"
                    controls
                    class="message-video"
                  >
                    <source :src="message.content" type="video/mp4">
                    您的浏览器不支持视频播放
                  </video>
                  <audio
                    v-else
                    controls
                    class="message-audio"
                  >
                    <source :src="message.content" type="audio/mpeg">
                    您的浏览器不支持音频播放
                  </audio>
                </div>
                <!-- 其他文件消息 -->
                <div v-else-if="message.msgType === 3" class="message-file" @click="handleFileDownload(message.content)">
                  <el-icon><Document /></el-icon>
                  <span class="file-name">{{ getFileName(message.content) }}</span>
                  <el-icon><Download /></el-icon>
                </div>
              </div>
            </div>
          </div>

          <!-- 输入框 -->
          <div class="chat-input">
            <div class="record-save-option">
              <el-checkbox v-model="saveRecord" @change="handleRecordSaveChange">保存聊天记录</el-checkbox>
            </div>
            <el-input
              v-model="chatInputMessage"
              type="textarea"
              :rows="3"
              placeholder="输入消息..."
              @keydown.enter.prevent="handleSendGlobalChatMessage"
            />
            <div class="input-actions">
              <div class="upload-actions">
                <el-upload
                  ref="imageUploadRef"
                  class="upload-item"
                  action=""
                  :show-file-list="false"
                  :auto-upload="false"
                  accept="image/*"
                  @change="handleImageSelected"
                >
                  <el-button type="primary" plain>
                    <el-icon><Picture /></el-icon>
                    图片
                  </el-button>
                </el-upload>

                <el-upload
                  ref="videoUploadRef"
                  class="upload-item"
                  action=""
                  :show-file-list="false"
                  :auto-upload="false"
                  accept="video/*,audio/*"
                  @change="handleMediaSelected"
                >
                  <el-button type="primary" plain>
                    <el-icon><VideoCamera /></el-icon>
                    音视频
                  </el-button>
                </el-upload>

                <el-upload
                  ref="fileUploadRef"
                  class="upload-item"
                  action=""
                  :show-file-list="false"
                  :auto-upload="false"
                  @change="handleFileSelected"
                >
                  <el-button type="primary" plain>
                    <el-icon><Document /></el-icon>
                    文件
                  </el-button>
                </el-upload>
              </div>
              <el-button type="primary" @click="handleSendGlobalChatMessage">发送</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { fetchVisitRecord } from '@/axios/api/user'
import VoiceCallDialog from '@/components/VoiceCallDialog.vue'
import wsClient, { MessageType } from '@/utils/websocket'
import { ElMessage } from 'element-plus'
import { postUploadFile } from '@/axios/api/upload'
import { Picture, VideoCamera, Document, Download } from '@element-plus/icons-vue'
import { getUserInfo } from '@/utils/webStorage'

// 语音通话相关响应式数据
const showIncomingCall = ref(false)
const incomingCallData = ref({})
const incomingCallBaseUrl = ref(window.config_global.MEETING_BASE_URL || 'http://localhost:3000')

// 聊天会话相关响应式数据
const showIncomingChatRequest = ref(false)
const incomingChatData = ref({})

// 全局聊天面板相关响应式数据
const showGlobalChat = ref(false)
const globalChatTitle = ref('文字答疑')
const globalChatMessages = ref([])
const globalChatSessionId = ref('')
const globalChatData = ref({})
const chatInputMessage = ref('')
const messageListRef = ref(null)
const imageUploadRef = ref(null)
const videoUploadRef = ref(null)
const fileUploadRef = ref(null)
const saveRecord = ref(false)

// 处理聊天记录保存选项变更
const handleRecordSaveChange = (val) => {
  const userInfo = getUserInfo()
  if (!userInfo.uid) {
    ElMessage.error('用户信息无效')
    return
  }

  const message = {
    type: 'record-confirm',
    data: {
      uid: userInfo.uid,
      type: 'sender',
      status: val ? 1 : 0,
      sessionId: globalChatSessionId.value
    }
  }
  wsClient.send(message.type, message.data)
}

// 处理聊天窗口关闭
const handleChatClose = () => {
  saveRecord.value = false
}

// 处理图片选择
const handleImageSelected = async (file) => {
  try {
    const formData = new FormData()
    formData.append('Image', file.raw)
    const data = await postUploadFile(formData)

    if (data?.result) {
      // 发送图片消息
      await handleSendGlobalChatMessage(data.result, 1)
      // 清除上传组件状态
      if (imageUploadRef.value) {
        imageUploadRef.value.clearFiles()
      }
    }
  } catch (error) {
    console.error('上传图片失败:', error)
    ElMessage.error('上传图片失败')
  }
}

// 处理音视频选择
const handleMediaSelected = async (file) => {
  try {
    const formData = new FormData()
    formData.append('Image', file.raw)
    const data = await postUploadFile(formData)

    if (data?.result) {
      // 发送音视频消息
      await handleSendGlobalChatMessage(data.result, 2)
      // 清除上传组件状态
      if (videoUploadRef.value) {
        videoUploadRef.value.clearFiles()
      }
    }
  } catch (error) {
    console.error('上传音视频失败:', error)
    ElMessage.error('上传音视频失败')
  }
}

// 处理文件选择
const handleFileSelected = async (file) => {
  try {
    const formData = new FormData()
    formData.append('Image', file.raw)
    const data = await postUploadFile(formData)

    if (data?.result) {
      // 发送文件消息
      await handleSendGlobalChatMessage(data.result, 3)
      // 清除上传组件状态
      if (fileUploadRef.value) {
        fileUploadRef.value.clearFiles()
      }
    }
  } catch (error) {
    console.error('上传文件失败:', error)
    ElMessage.error('上传文件失败')
  }
}

// 处理接收到的语音通话请求
const handleVoiceCallMessage = (data) => {
  console.log('收到语音通话请求:', data)

  try {
    // 设置来电数据
    incomingCallData.value = {
      senderId: data.senderId,
      receiverId: data.receiverId,
      senderName: data.senderName,
      receiverName: '我', // 接收方就是当前用户
      questionId: data.questionId,
      startTime: Date.now(),
      recordId: data.recordId,
      isIncoming: true, // 标记为来电
      isVideo: false // 标记为语音通话
    }

    // 修改base URL为 /incoming
    incomingCallBaseUrl.value = window.config_global.MEETING_BASE_URL || 'http://localhost:3000'

    // 显示来电弹窗
    showIncomingCall.value = true

    // 如果浏览器支持通知API，可以显示系统通知
    if ('Notification' in window && Notification.permission === 'granted') {
      new Notification('语音通话请求', {
        body: `${data.senderName} 正在呼叫您`,
        icon: '/favicon.ico'
      })
    }
  } catch (error) {
    console.error('处理语音通话请求失败:', error)
    ElMessage.error('处理语音通话请求失败')
  }
}

// 处理接收到的视频通话请求
const handleVideoCallMessage = (data) => {
  console.log('收到视频通话请求:', data)

  try {
    // 设置来电数据
    incomingCallData.value = {
      senderId: data.senderId,
      receiverId: data.receiverId,
      senderName: data.senderName,
      receiverName: '我', // 接收方就是当前用户
      questionId: data.questionId,
      startTime: Date.now(),
      recordId: data.recordId,
      isIncoming: true, // 标记为来电
      isVideo: true // 标记为视频通话
    }

    // 修改base URL为 /incoming
    incomingCallBaseUrl.value = window.config_global.MEETING_BASE_URL || 'http://localhost:3000'

    // 显示来电弹窗
    showIncomingCall.value = true

    // 如果浏览器支持通知API，可以显示系统通知
    if ('Notification' in window && Notification.permission === 'granted') {
      new Notification('视频通话请求', {
        body: `${data.senderName} 正在呼叫您`,
        icon: '/favicon.ico'
      })
    }
  } catch (error) {
    console.error('处理视频通话请求失败:', error)
    ElMessage.error('处理视频通话请求失败')
  }
}

// 处理通话同意消息
const handleCallAgreeMessage = (data) => {
  console.log('收到通话同意消息:', data)
}

// 处理通话拒绝消息
const handleCallRejectMessage = (data) => {
  console.log('收到通话拒绝消息:', data)
  const reason = data.reason || '对方拒绝了通话'

  // 如果当前正在显示通话弹窗，则关闭它
  if (showIncomingCall.value) {
    showIncomingCall.value = false
  }
}

// 处理通话结束消息
const handleCallEndMessage = (data) => {
  console.log('收到通话结束消息:', data)

  // 如果当前正在显示通话弹窗，则关闭它
  if (showIncomingCall.value) {
    showIncomingCall.value = false
  }
}

// 处理生成会话请求消息
const handleGenSessionMessage = (data) => {
  console.log('收到生成会话请求:', data)

  try {
    // 设置来电聊天数据
    incomingChatData.value = {
      senderId: data.senderId,
      receiverId: data.receiverId,
      questionId: data.questionId,
      senderName: data.senderName || '用户'
    }

    // 这里可以选择自动接受或显示确认弹窗
    // 目前直接接受并生成sessionId
    const sessionId = `session_${Date.now()}_${data.senderId}_${data.receiverId}`

    // 发送session-id消息给双方
    wsClient.send(MessageType.SESSION_ID, {
      sessionId: sessionId,
      senderId: data.senderId,
      receiverId: data.receiverId,
      questionId: data.questionId
    })

    console.log('聊天会话已创建:', sessionId)

  } catch (error) {
    console.error('处理生成会话请求失败:', error)
    ElMessage.error('处理聊天请求失败')
  }
}

// 处理会话ID消息
const handleSessionIdMessage = (data) => {
  console.log('收到会话ID消息:', data)

  try {
    if (data.sessionId) {
      // 设置全局聊天状态
      globalChatSessionId.value = data.sessionId
      globalChatData.value = {
        senderId: data.senderId,
        receiverId: data.receiverId,
        questionId: data.questionId
      }

      // 设置聊天标题
      if (data.senderName) {
        globalChatTitle.value = `与 ${data.senderName} 的文字答疑`
      }

      // 显示聊天面板
      showGlobalChat.value = true

      ElMessage.success('聊天会话已建立')
      console.log('全局聊天面板已打开, sessionId:', data.sessionId)
    }
  } catch (error) {
    console.error('处理会话ID消息失败:', error)
  }
}

// 处理聊天消息
const handleChatMessage = (data) => {
  console.log('收到聊天消息:', data)

  try {
    // 验证消息数据
    if (!data.sessionId || !data.content) {
      console.error('聊天消息数据不完整:', data)
      return
    }

    // 只处理当前会话的消息
    if (data.sessionId !== globalChatSessionId.value) {
      console.log('忽略其他会话的消息')
      return
    }

    // 添加到全局消息列表
    const message = {
      id: Date.now() + Math.random(), // 确保唯一性
      senderId: data.senderId,
      receiverId: data.receiverId,
      senderName: data.senderName,
      content: data.content,
      msgType: data.msgType || 0,
      timestamp: Date.now(),
      isSelf: false // 接收到的消息都是对方发送的
    }

    globalChatMessages.value.push(message)

    // 自动滚动到底部
    setTimeout(() => {
      scrollToBottom()
    }, 100)

    // 显示消息通知
    if (data.senderName && data.content) {
      ElMessage.info(`收到来自 ${data.senderName} 的消息`)
    }

    // 如果浏览器支持通知API，可以显示系统通知
    if ('Notification' in window && Notification.permission === 'granted') {
      new Notification(`来自 ${data.senderName || '对方'} 的消息`, {
        body: data.content,
        icon: '/favicon.ico'
      })
    }

  } catch (error) {
    console.error('处理聊天消息失败:', error)
  }
}

// 发送全局聊天消息
const handleSendGlobalChatMessage = async (content, msgType = 0) => {
  // 如果是文本消息，使用输入框的内容
  if (msgType === 0) {
    if (!chatInputMessage.value.trim()) {
      ElMessage.warning('请输入消息内容')
      return
    }
    content = chatInputMessage.value.trim()
  }

  // 如果没有内容，不发送
  if (!content) {
    return
  }

  if (!globalChatSessionId.value) {
    ElMessage.error('聊天会话未建立')
    return
  }

  try {
    // 获取用户信息
    const userInfo = getUserInfo()
    if (!userInfo.uid || !userInfo.username) {
      ElMessage.error('用户信息无效')
      return
    }

    // 判断当前用户是发起方还是接收方，设置正确的receiverId
    const isOriginalSender = userInfo.uid === globalChatData.value.senderId
    const targetUserId = isOriginalSender
      ? globalChatData.value.receiverId  // 如果是发起方，发送给接收方
      : globalChatData.value.senderId    // 如果是接收方，发送给发起方

    console.log('发送消息身份判断:', {
      currentUserId: userInfo.uid,
      originalSenderId: globalChatData.value.senderId,
      originalReceiverId: globalChatData.value.receiverId,
      isOriginalSender: isOriginalSender,
      targetUserId: targetUserId
    })

    // 构建消息数据
    const messageData = {
      senderId: userInfo.uid,
      receiverId: targetUserId,
      senderName: userInfo.username,
      sessionId: globalChatSessionId.value,
      questionId: globalChatData.value.questionId,
      content: content,
      msgType: msgType // 0文本 1图片 2音视频 3其他文件
    }

    console.log('发送全局聊天消息:', messageData)

    // 在线状态检查
    const isOnline = await wsClient.checkOnlineStatus(userInfo.uid, targetUserId)
    if (!isOnline) {
      ElMessage.warning('对方不在线，消息未发送')
      return
    }

    // 通过WebSocket发送消息
    const sendResult = wsClient.send(MessageType.CHAT_MESSAGE, messageData)

    if (!sendResult) {
      ElMessage.error('发送消息失败，请检查网络连接')
      return
    }

    // 添加到本地消息列表
    const localMessage = {
      id: Date.now() + Math.random(),
      ...messageData,
      timestamp: Date.now(),
      isSelf: true
    }

    globalChatMessages.value.push(localMessage)

    // 如果是文本消息，清空输入框
    if (msgType === 0) {
      chatInputMessage.value = ''
    }

    // 自动滚动到底部
    setTimeout(() => {
      scrollToBottom()
    }, 100)

    console.log('消息发送成功')

  } catch (error) {
    console.error('发送全局聊天消息失败:', error)
    ElMessage.error('发送消息失败')
  }
}

// 格式化消息时间
const formatMessageTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}

// 滚动到底部
const scrollToBottom = () => {
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight
  }
}

// 判断是否是视频文件
const isVideoFile = (url) => {
  const videoExtensions = ['.mp4', '.webm', '.ogg']
  return videoExtensions.some(ext => url.toLowerCase().endsWith(ext))
}

// 从URL中获取文件名
const getFileName = (url) => {
  try {
    const urlObj = new URL(url)
    const pathname = urlObj.pathname
    return pathname.substring(pathname.lastIndexOf('/') + 1)
  } catch (error) {
    return url.substring(url.lastIndexOf('/') + 1)
  }
}

// 处理文件下载
const handleFileDownload = (url) => {
  try {
    // 创建一个隐藏的a标签
    const link = document.createElement('a')
    link.href = url
    link.download = getFileName(url) // 设置下载文件名
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败')
  }
}

onMounted(() => {
  fetchVisitRecord()

  // 注册全局语音通话消息处理器
  wsClient.on(MessageType.VOICE_CALL, handleVoiceCallMessage)
  wsClient.on(MessageType.VIDEO_CALL, handleVideoCallMessage)
  wsClient.on(MessageType.CALL_AGREE, handleCallAgreeMessage)
  wsClient.on(MessageType.CALL_REJECT, handleCallRejectMessage)
  wsClient.on(MessageType.CALL_END, handleCallEndMessage)

  // 注册聊天消息处理器
  wsClient.on(MessageType.GEN_SESSION, handleGenSessionMessage)
  wsClient.on(MessageType.SESSION_ID, handleSessionIdMessage)
  wsClient.on(MessageType.CHAT_MESSAGE, handleChatMessage)

  // 请求通知权限（如果还没有权限）
  if ('Notification' in window && Notification.permission === 'default') {
    Notification.requestPermission()
  }
})

onBeforeUnmount(() => {
  // 移除全局语音通话消息处理器
  wsClient.off(MessageType.VOICE_CALL, handleVoiceCallMessage)
  wsClient.off(MessageType.VIDEO_CALL, handleVideoCallMessage)
  wsClient.off(MessageType.CALL_AGREE, handleCallAgreeMessage)
  wsClient.off(MessageType.CALL_REJECT, handleCallRejectMessage)
  wsClient.off(MessageType.CALL_END, handleCallEndMessage)

  // 移除聊天消息处理器
  wsClient.off(MessageType.GEN_SESSION, handleGenSessionMessage)
  wsClient.off(MessageType.SESSION_ID, handleSessionIdMessage)
  wsClient.off(MessageType.CHAT_MESSAGE, handleChatMessage)
})
</script>

<style>
main {
  height: 100vh;
  overflow-y: auto;
  /* scroll-behavior: smooth; */
}

/* 確保內容區域可以正常滾動 */
.main-content {
  min-height: 100%;
  position: relative;
}

/* 自定義滾動條樣式 */
main::-webkit-scrollbar {
  width: 8px;
}

main::-webkit-scrollbar-track {
  background: #f1f1f1;
}

main::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

main::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* 全局聊天面板样式 */
.global-chat-dialog :deep(.el-dialog) {
  height: 650px;
  min-height: 500px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.global-chat-dialog :deep(.el-dialog__body) {
  flex: 1;
  padding: 0;
  overflow: hidden;
  min-height: 400px;
}

.chat-container {
  height: 100%;
  min-height: 400px;
  display: flex;
  flex-direction: column;
}

.chat-main {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 300px;
  max-height: 450px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 300px;
  max-height: 450px;
}

.message-item {
  margin-bottom: 16px;
  display: flex;
}

.message-item.self {
  justify-content: flex-end;
}

.message-content {
  max-width: 75%;
  background: white;
  border-radius: 18px;
  padding: 12px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e9ecef;
}

.message-item.self .message-content {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  color: #1565c0;
  border: 1px solid #90caf9;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-size: 12px;
  opacity: 0.7;
}

.message-text {
  word-break: break-word;
  line-height: 1.4;
}

.message-media {
  margin-top: 8px;
}

.message-image {
  max-width: 240px;
  max-height: 240px;
  border-radius: 8px;
  cursor: pointer;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
  color: #909399;
}

.message-video {
  max-width: 320px;
  max-height: 240px;
  border-radius: 8px;
}

.message-audio {
  width: 240px;
  margin-top: 4px;
}

.message-file {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: #f5f7fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.message-file:hover {
  background: #e9ecef;
}

.file-name {
  flex: 1;
  margin: 0 8px;
  color: #1565c0;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #e9ecef;
  background: #fafbfc;
}

.record-save-option {
  padding: 8px 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.input-actions {
  margin-top: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-actions {
  display: flex;
  gap: 8px;
}

.upload-item {
  margin: 0 !important;
}

.upload-actions :deep(.el-button) {
  margin: 0;
  height: 36px;
  padding: 8px 12px;
  border-radius: 8px;
}

.upload-actions :deep(.el-icon) {
  margin-right: 4px;
}

.input-actions :deep(.el-button--primary) {
  border-radius: 8px;
  padding: 8px 20px;
  height: 36px;
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
  border: none;
  box-shadow: 0 2px 4px rgba(0, 123, 255, 0.3);
}

.input-actions :deep(.el-button--primary):hover {
  background: linear-gradient(135deg, #0056b3 0%, #004085 100%);
  box-shadow: 0 4px 8px rgba(0, 123, 255, 0.4);
}

.upload-actions :deep(.el-button--primary) {
  background: white;
  border: 1px solid #dcdfe6;
  color: #606266;
  box-shadow: none;
}

.upload-actions :deep(.el-button--primary:hover) {
  background: #f5f7fa;
  border-color: #c0c4cc;
  color: #409eff;
}

.chat-input :deep(.el-textarea__inner) {
  border-radius: 12px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  resize: none;
}

.chat-input :deep(.el-textarea__inner):focus {
  border-color: #007bff;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.2);
}

/* 滚动条样式 */
.message-list::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
